package org.hepeng.workx.util.concurrent;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author he peng
 */
public class NamedThreadFactory implements ThreadFactory {

    private static final AtomicInteger POOL_SEQ = new AtomicInteger(1);
    private final AtomicInteger mThreadNum = new AtomicInteger(1);


    private String threadNamePrefix;
    private final boolean daemo;
    private final ThreadGroup threadGroup;

    public NamedThreadFactory() {
        this("pool-" + POOL_SEQ.getAndIncrement(), false);
    }

    public NamedThreadFactory(String threadNamePrefix) {
        this(threadNamePrefix, false);
    }

    public NamedThreadFactory(String prefix, boolean daemo) {
        this.threadNamePrefix = prefix + "-thread-";
        this.daemo = daemo;
        SecurityManager s = System.getSecurityManager();
        this.threadGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
    }

    @Override
    public Thread newThread(@NotNull Runnable r) {
        String name = this.threadNamePrefix + mThreadNum.getAndIncrement();
        Thread ret = new Thread(this.threadGroup , r , name , 0);
        ret.setDaemon(this.daemo);
        return ret;
    }

    public ThreadGroup getThreadGroup() {
        return this.threadGroup;
    }
}
